<template>
    <!--  表单  -->
    <div class="space-container">
        <span class="title-span">
          <span>目录列表</span>
        </span>
        <table-common
          :loading="loading"
          :columns="exampleColumns"
          :table-data="tabeData"
          row-key="id"
          lazy
          :load="load"
          :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
          stripe
          :pagination="false"
          default-expand-all
          height="100%"
        >
          <template #action="{ row }">
            <el-button
              class="link-btn"
              @click="handleEdit(row,0)"
              link
              type="primary"
              size="small"
              v-if="row.level != 6"
            >增加下级</el-button>
            <el-button
              class="link-btn"
              @click="transferBtn(row)"
              link
              type="primary"
              size="small"
              :style="{display: row.parentId == -1 ? 'none' : ''}"
            >转移</el-button>
            <el-button
              class="link-btn"
              @click="handleEdit(row,1)"
              link
              type="primary"
              size="small"
              :style="{display: row.parentId == -1 ? 'none' : ''}"
            >编辑</el-button>

            <el-popconfirm :title="row.children?'该目录下有子目录，是否删除?':'是否删除?'"  @confirm="() => handleDelete(row)">
              <template #reference>
                <el-button
                  class="link-btn"
                  link
                  type="primary"
                  size="small"
                  :style="{display: row.parentId == -1 ? 'none' : ''}"
                >删除</el-button>
              </template>
            </el-popconfirm>
            <el-button
              class="link-btn"
              @click="handleHistory(row)"
              link
              type="primary"
              size="small"
              :style="{display: row.parentId == -1 ? 'none' : ''}"
            >历史记录</el-button>
          </template>
        </table-common>
        <!--  增加及编辑弹窗  -->
          <edit-dialog
            class="maintenance"
            :centerDialogVisible="thresholdDialogVisible"
            :tilte="addTilte"
            :key="timer"
            :defaultButton="false"
            :width="'500'"
            @cancel="handleCancel"
            :close-on-click-modal="false"
          >
            <template #content>
              <el-form ref="retrievedFormRef" :model="retrievedForm" :rules="rules" label-position="right" label-width="100px">
                <el-form-item label="父级目录:" prop="parentId">
                  <span>{{parentClassification}}</span>
                </el-form-item>
                <el-form-item label="目录名称:" prop="name">
                  <el-input v-model="retrievedForm.name" maxlength="15" placeholder="请输入目录名称"/>
                </el-form-item>
                <el-form-item label="是否有效:" prop="isValid">
                  <el-radio-group v-model="retrievedForm.isValid" class="ml-4">
                    <el-radio label="1" size="large">是</el-radio>
                    <el-radio label="0" size="large">否</el-radio>
                  </el-radio-group>
                </el-form-item>
              </el-form>
            </template>
            <template #custom>
              <span class="dialog-footer">
                <el-button @click="handleCancel">取消</el-button>
                <el-button type="primary" @click="handleSubmit" :loading="saveBtn">保存</el-button>
              </span>
            </template>
          </edit-dialog>
        <!--  转移弹窗    -->
        <edit-dialog
        class="maintenance"
        :centerDialogVisible="transferDialogVisible"
        :tilte="addTransferTilte"
        :key="timer"
        :defaultButton="false"
        :width="'600'"
        @cancel="handleCancel"
        :close-on-click-modal="false"
      >
          <template #content>
            <el-tree
              ref="treeRef"
              class="filter-tree"
              :data="companyData"
              :props="defaultProps"
              default-expand-all
              :expand-on-click-node="false"
              :check-strictly="true"
              @check="treeCheck"
              node-key="id"
              show-checkbox
            ><template #default="{ node, data }">
              <span class="span-ellipsis">
                <span>{{ node.label }}</span>
                </span>
            </template>

            </el-tree>
          </template>
          <template #custom>
            <span class="dialog-footer">
              <el-button @click="handleCancel">取消</el-button>
              <el-button type="primary" @click="handleTransferSubmit" :loading="saveBtn">保存</el-button>
            </span>
          </template>
      </edit-dialog>
        <!--  历史记录弹窗    -->
        <edit-dialog
        class="maintenance"
        :centerDialogVisible="historyDialogVisible"
        :tilte="addHistoryTilte"
        :key="timer"
        :defaultButton="false"
        :width="'1000'"
        @cancel="handleCancel"
        :close-on-click-modal="false"
      >
        <template #content>
          <table-common
            :loading="loading"
            :columns="exampleHistoryColumns"
            :table-data="tabeData2"
            size="small"
            :pagination="false"
            stripe
            :height="'200'"
          >
          </table-common>
        </template>
        <template #custom>
            <span class="dialog-footer">
              <el-button @click="handleCancel">关闭</el-button>
            </span>
        </template>
      </edit-dialog>
        <!--   确认弹窗     -->
        <edit-dialog
            :centerDialogVisible="centerDialogTips"
            tilte="提示"
            :key="timer"
            :width="'500'"
            align-center
            :defaultButton="false"
            @cancel="previewCancel"
        >
            <template #content>
                <span style="font-size: 0.95rem;">{{tipsContent}}</span>
            </template>
            <template #custom>
          <span class="dialog-footer">
                <el-button @click="handleCancel">取消</el-button>
                <el-button type="primary" @click="tipsTransferSubmit" :loading="saveBtn">确定</el-button>
              </span>
            </template>
        </edit-dialog>
    </div>
</template>

<script setup lang="ts">
  // 需要导入watch监听
  import { computed, ref, onBeforeMount, nextTick, watch, reactive, onMounted } from 'vue'
  // 以下两项需要导入
  import { ElTree, ElMessage } from 'element-plus'
  import { Download, Search } from '@element-plus/icons-vue'
  // 7-18修改LayoutCard 页面，hasButton参数为false时显示为弹窗样式，为true时显示为搜索栏样式
  import LayoutCard from '@/components/LayoutCard/index.vue'
  import TableCommon from '@/components/TableCommon/index.vue'
  import { exampleColumns, exampleHistoryColumns } from './config/columns'
  import { usePagination } from 'vue-request'
  import editDialog from '@/components/editDialog/index.vue' // 弹窗样式
  import { useStore } from 'vuex'
  import type { FormInstance,FormRules } from 'element-plus'
  import FilterBar from '@/components/FilterBar/index.vue'
  import { getChildrenDirectory, addSubordinates, updateSubordinates, deleteSubordinates, getHistory, transferSubordinates } from '@/api/knowledge/space'
  import { getResource } from "@/api/resource";
  import { dayjs } from 'element-plus'
  // import VueOfficeDocx from '@vue-office/docx'
  // import '@vue-office/docx/lib/index.css'
  import VueOfficeExcel from '@vue-office/excel'
  import '@vue-office/excel/lib/index.css'
  import {forEach, keys} from "lodash";
  const Service = (data: ListParams) => {};
  const {
    loading,
  } = usePagination(Service, {
    manual: true,
    pagination: {
      currentKey: 'pageNum',
      pageSizeKey: 'pageSize',
      totalKey: 'data.total'
    }
  });
  // 新增弹窗是否打开
  const centerDialogVisible = ref(false);
  // 新增下级弹窗
  const thresholdDialogVisible = ref(false);
  // 转移弹窗
  const transferDialogVisible = ref(false);
  // 历史记录弹窗
  const historyDialogVisible = ref(false);
  const addTilte = ref(""); // 新增编辑弹窗名称
  const addTransferTilte = ref(""); // 转移弹窗名称
  const addHistoryTilte = ref(""); // 历史记录弹窗名称
  const parentClassification = ref("");// 父子分类回显
  // 提示弹窗
  const centerDialogTips = ref(false);
  const tipsContent = ref("");
  // 时间戳，用于确保弹窗页面能加载不同的界面
  const timer = ref();
  // 请求用户的权限树
  const { getters } = useStore();
  const Users = computed(() => getters['user/getUserInfo']);
  //表格数据
  const tabeData = ref<any>([]);
  // 历史记录表格数据
  const tabeData2 = ref<any>([]);
  const saveBtn = ref(false);
  const defaultProps = {
      children: 'children',
      label: 'name',
      disabled:'disabled'
  };
  const deleteId = ref<any>(); // 删除id
  //排序规则
  const isOrder = ref([]);
  const store = useStore();
  const userInfo = computed(() => store.state.user.userInfo);
  //当前选中树节点
  const eventType = {
      id: '',
      parentId: '',
      catalogueId:'',
      parentName:'',
      catalogueName:'',
      level:0,
      node:[],
      node1:{},
      createUser: {
          id: userInfo.value.userId,
          name: userInfo.value.name,
          userName: userInfo.value.userName,
          organId: userInfo.value.organId || '',
          organName: userInfo.value.organName || ''
      },
  };
  // 增加/编辑
  interface RuleForm {
      parentId: string;
      name: string;
      isValid: string;
      createUser: object,
      catalogueId:string,
      id:string,
    parentName:string
  }
  const retrievedForm = reactive<RuleForm>({
    parentId: '',
    name: '',
    isValid: '1',
    createUser: {},
    updateUser: {},
    catalogueId:'',
    id:'',
    parentName:'',
    level:0,
  });
  // 空间转移---树形
  const companyData = ref([]);

  // 表单验证
  const rules = reactive<retrievedForm>({
      name: [
          { required: true, message: '请输入空间名称', trigger: 'blur' },
      ],
  });

  /**
   * 取消按钮
   */
  const handleCancel = () => {
      thresholdDialogVisible.value = false;
      transferDialogVisible.value = false;
      historyDialogVisible.value = false;
      centerDialogTips.value = false;
      saveBtn.value = false;
  };

  /**
   * 增加编辑---保存按钮
   */
  const handleSubmit = () => {
      if (!retrievedForm.name){
          ElMessage.error('请填写空间名称');
      } else {
          saveBtn.value = true;
          if (addTilte.value == "增加下级") {
              addSubordinates(retrievedForm).then((res:any)=>{
                  if (res.code == 1) {
                      ElMessage.success('增加下级成功');
                      thresholdDialogVisible.value = false;
                      saveBtn.value = false;
                      getData();
                  } else {
                      ElMessage.error(res.message?res.message:'增加下级失败');
                      thresholdDialogVisible.value = false;
                      saveBtn.value = false;
                  }
              })
          } else if (addTilte.value == "修改") {
              updateSubordinates(retrievedForm).then((res)=> {
                  if (res.code == 1) {
                      ElMessage.success('编辑成功');
                      thresholdDialogVisible.value = false;
                      saveBtn.value = false;
                      getData();
                  } else {
                      ElMessage.error(res.message?res.message:'编辑失败');
                      thresholdDialogVisible.value = false;
                      saveBtn.value = false;
                  }
              })
          }
      }
  };

  /**
   * 编辑
   */
  const handleEdit = (row,type) => {
      retrievedForm.name = "";
      retrievedForm.id = "";
    // 增加下级
    if (type == 0) {
        addTilte.value = "增加下级";
        parentClassification.value = row.name;
        retrievedForm.level = row.level+1
        retrievedForm.parentId = row.parentId==-1?undefined:row.id;
        retrievedForm.updateUser = null;
        retrievedForm.createUser ={
            id: userInfo.value.userId,
            name: userInfo.value.name,
            userName: userInfo.value.userName,
            organId: userInfo.value.organId || '',
            organName: userInfo.value.organName || ''
        };
        retrievedForm.catalogueId = row.catalogueId;
        retrievedForm.parentName = row.name;
    } else if (type == 1) {
        //编辑
        addTilte.value = "修改";
        retrievedForm.id = row.id;
        parentClassification.value = row.parentName;
        retrievedForm.parentId = row.parentId;
        retrievedForm.isValid = String(row.isValid);
        retrievedForm.name=row.name
        retrievedForm.parentName=row.parentName
        retrievedForm.createUser = null;
        retrievedForm.updateUser ={
            id: userInfo.value.userId,
            name: userInfo.value.name,
            userName: userInfo.value.userName,
            organId: userInfo.value.organId || '',
            organName: userInfo.value.organName || ''
        };
        retrievedForm.catalogueId = row.catalogueId;
    }
      thresholdDialogVisible.value = true;
  };

  /**
   * 转移
   */
  const transferBtn = async (row:any) => {
      const rowData = JSON.parse(JSON.stringify(row));
      saveBtn.value = false;
      eventType.parentId='';
      eventType.id = rowData.id;
      addTransferTilte.value = "空间转移";
      rowData.disabled=true;

      companyData.value =JSON.parse(JSON.stringify(tabeData.value));
      let condition={
          key:'id',
          value:row.id
      }
      const a = findByCondition(companyData.value,condition)
      recursion(a.value)
      transferDialogVisible.value = true;
      selectNodeList.value=[]
      eventType.node1={}
      eventType.node1=JSON.parse(JSON.stringify(row))

  };
  let result = ref(null);
  const findByCondition = (data, condition)=>{
      for (let i = 0; i < data.length; i++) {
          var node = data[i];
          if (node[condition.key] === condition.value) { // 为true跳出循环
              result.value = node;
              break;
          } else { // 相反则去判断当前值是否有children 如果有children则继续循环
              if (node.children != null) {
                  findByCondition(node.children, condition);
              }
          }
      }
      return result;
  }
  const recursion=(row)=>{
    if(row.children&&row.children.length>0){
        row.disabled=true
      row.children.forEach(res=>{
        res.disabled=true;
        recursion(res)
      })
    } else {
        row.disabled=true;
    }
  }
  /**
   * 树结构单选
   */
    const treeRef=ref();
    const treeCheck = (node:any, list:any) => {

          if (list.checkedKeys.length == 2) {
              treeRef.value.setCheckedKeys([node.id]);
          }
          if (node.parentId == -1) {
              eventType.parentId = '0';
              eventType.catalogueId = node.catalogueId;
          } else {
              eventType.parentId = node.id;
              eventType.catalogueId = node.catalogueId;
          }
         let thisNode = treeRef.value.getNode(node.id);
         let keys = [node];
         if (thisNode.checked) {
             for (let i = thisNode.level; i > 1; i--) {
                 // 当前子节点选中，取消勾选父节点
                 treeRef.value.setChecked(thisNode.parent, false)
                 // 判断是否有父级节点
                 if (!thisNode.parent.checked) {
                     // 父级节点未被选中，则将父节点替换成当前节点，往上继续查询，并将此节点key存入keys数组
                     thisNode = thisNode.parent
                     keys.unshift(thisNode.data)
                 }
             }
             eventType.level = node.level+1;
             //修改层级
             selectNodeList.value=[]
             const nodes=JSON.parse(JSON.stringify(eventType.node1))
             if(nodes.children&&nodes.children.length>0){
                 rebuildLevel(nodes.children,eventType.level)
             }
         }
        const a = keys.shift();
        let parentsName = ""
      if(keys.length==0){
          parentsName =node.name;

      }else{
        keys.forEach((items)=>{
          parentsName +='/' + items.name;
        })
      }

        eventType.parentName = parentsName;
        eventType.catalogueName = a.name;


  };
  //修改转移选中的目录层级
  const selectNodeList=ref<any>([])
  const  rebuildLevel=(data:any,level)=>{
      data.forEach(item=>{
          item.level=level+1
          selectNodeList.value.push({
              id:item.id,
              level:item.level
          })
          if(item.children&&item.children.length>0){
              rebuildLevel(item.children,item.level)
          }
      })
  }
  /**
   * 转移---保存按钮
   */
  const handleTransferSubmit = () => {
      const  tt=selectNodeList.value.filter((res)=>{
          return res.level>6
      })
      console.log("--11--",selectNodeList)
      if(tt.length>0){
          ElMessage.error('不能转移到当前目录');
          return
      }
      if(eventType.level>6){
          ElMessage.error('不能转移到当前目录');
          return
      }
      eventType.node=selectNodeList.value
      saveBtn.value = true;
      if (eventType.parentId != "") {
          transferSubordinates(eventType).then((res:any)=>{
              if (res.code == 1) {
                  ElMessage.success('转移成功');
                  saveBtn.value = false;
                  transferDialogVisible.value = false;
                  getData();
              } else {
                  ElMessage.error(res.message||'转移失败');
                  saveBtn.value = false;
                  transferDialogVisible.value = false;
              }
          });
      } else {
          ElMessage.error('请选择需要转移的目录');
          saveBtn.value = false;
      }
  };

  /**
   * 删除
   */
  const handleDelete = async (row:any) => {
      deleteId.value = '';
      //centerDialogTips.value = true;
      //tipsContent.value = "确定要删除该目录吗？";
      deleteId.value = row.id;
    tipsTransferSubmit()
  };

  /**
   * 提示框确认按钮
   */
  const tipsTransferSubmit = () => {
      saveBtn.value = true;
      loading.value=true
      deleteSubordinates(deleteId.value).then((res:any)=>{
          if (res.code == 1) {
              ElMessage.success('删除成功');
              centerDialogTips.value = false;
              saveBtn.value = false;
              loading.value=false
              getData();
          } else {
              ElMessage.error(res.message?res.message:'删除失败');
              centerDialogTips.value = false;
              saveBtn.value = false;
              loading.value=false
          }
      });
  };

  /**
   * 历史记录
   */
  const handleHistory = async (row:any) => {
      getHistory(row.id).then((res:any)=>{
          if (res.code == 1) {
              tabeData2.value = res.data;
          } else {
              ElMessage.error('历史记录查询失败');
          }
      });
      addHistoryTilte.value = "历史记录";
      historyDialogVisible.value = true;
  };
  const organizeTree1 = computed(() => getters['user/getOrganTree']);
  const organizeTree = ref([]);
  // 获取表格数据
  const getData = async () => {
      loading.value = true;
      // 获取组织架构
      tabeData.value=[];
      organizeTree.value=JSON.parse(JSON.stringify(organizeTree1.value))
      const datas=ergodicTree(organizeTree.value,'',[])
        datas.forEach((item:any)=>{
          item.name=item.data.name;
          item.createUser='/';
          item.createTime="/";
          item.childQuantity=0;
          item.fileQuantity=0;
          item.isValid="/";
          item.parentId=-1;
          item.children=[];
          item.catalogueId=item.data.organId;
          item.id = item.data.organId;
          item.level
          tabeData.value.push(item);
          getChildrenDirectoryList(item.data.organId)
      })
  };
  const ergodic=ref([])
  const ergodicTree=(datas:any,name:any,list:any)=>{
      datas.forEach((item:any)=>{
      item.data.name=name?name+'/'+item.data.name:item.data.name;
      item.level=0
      if(item.children&&item.children.length>0){
        ergodicTree(item.children,item.data.name,list)
      }else{
        list.push(item)
      }
    })
    return list
  };
  const getChildrenDirectoryList=(orId:string)=>{
      // 获取子级数据
      getChildrenDirectory(orId).then((res) => {
          const getTableData = res.data; // 子级数据
            getTableData.forEach((item:any)=>{
                tabeData.value.forEach((item1:any)=>{

                    if(item.catalogueId == item1.catalogueId){

                      item1.childQuantity=getTableData.length
                      item1.fileQuantity=item.catalogueFileNum
                      item1.children.push(item);

                  }

                })
            });
          loading.value = false;
      });
  };
  // 页面挂载时获取表格数据
  onMounted(async () => {
      getData();
  });

</script>

<style lang="less" scoped>
  ::-webkit-scrollbar {
    width: 5px;
  }
  ::-webkit-scrollbar-thumb {
    background-color: #dddee0;
  }
    ::-webkit-scrollbar {display: none}
  ::v-deep .el-tree--highlight-current .el-tree-node.is-current>.el-tree-node__content {
      width: 100%;
    }
  ::v-deep .el-tree-node:focus > .el-tree-node__content {
        // background-color: #5daaf0; //背景色
        width: 100%;
      }
    //::v-deep .el-tree>.el-tree-node {
    //  overflow-x: hidden;
    //  overflow-y: hidden;
    //}
    //  ::v-deep .el-tree-node > .el-tree-node__children {
	  //    overflow: visible;
    //  }

    .space-container {
      height: 86%;
      background: #fff;
      margin: 15px;
      border-radius: 15px;
      .title-span {
        display: block;
        width: 100%;
        padding: 20px 0 30px;
        background: #fff;
        span {
          display: block;
          border-left: 5px solid #2e7cf1;
          color: #353A42;
          font-weight: bold;
          padding-left: 5px;
        }
      }
    }
</style>
